package com.srt;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Arrays;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeMap;

import javax.jws.WebService;

import org.apache.commons.lang3.StringUtils;

@WebService(targetNamespace = "http://srt.com/", endpointInterface = "com.srt.DataServiceProjectSEI", portName = "DataWebServicePort", serviceName = "DataWebServiceService")
public class DataWebService implements DataServiceProjectSEI {
	public void dataInTen(String file) {
		//InputQuery.toData(parseWordsToString(file));
		System.out.println("PATH="+file);
		File data = new File(file);
		if(data.exists()){
			System.out.println("SERVER: such file exists - "+ data.getAbsolutePath());
			System.out.println(parseWordsToString(data));
		} else {
			System.out.println("SERVER: no such file - "+data.getAbsolutePath());
		}
	}

	private static String parseWordsToString(File inputFile) {
		StringBuilder result = new StringBuilder();
		if (inputFile.exists()) {
			try {
				BufferedReader reader = new BufferedReader(new FileReader(
						inputFile));

				String tempLine;

				while ((tempLine = reader.readLine()) != null) {
					result.append(tempLine + " ");
				}
				reader.close();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return lineParsetoTen(result.toString());

	}

	private static String lineParsetoTen(String s) {
		s = s.replaceAll("[^a-zA-Z]", " ");
		s = s.toLowerCase();
		System.out.println(s);
		s = " " + s + " ";
		String element;
		StringTokenizer tokenizer = new StringTokenizer(s, " ");
		TreeMap<Double, String> map = new TreeMap<Double, String>();
		double increment = 0;
		while (tokenizer.hasMoreElements()) {
			element = (String) tokenizer.nextElement();
			double matches = StringUtils.countMatches(s, " " + element + " ");
			if (!map.containsValue(element)) {
				map.put(matches + increment, element);
				increment = increment + 0.0000001;
			}
		}
		StringBuilder builder = new StringBuilder();
		SortedSet<Double> values = map.descendingKeySet();
		for (Double i : values) {
			builder.append((int) i.longValue() + "-" + map.get(i) + " ");
		}
		return getTen(builder.toString());
	}

	private static String getTen(String text) {
		StringBuilder builder = new StringBuilder();
		String[] ss;
		ss = text.split(" ");
		System.out.println(Arrays.toString(ss));
		int j = 0;
		for (String str : ss) {
			if (j < 10) {
				builder.append(str);
				builder.append(" ");
				j++;
			} else
				break;
		}
		return builder.toString();
	}

}
